/* eslint-disable quotes */
/* eslint-disable quote-props */
import React, { useEffect, useState } from 'react';
import { observer } from 'mobx-react-lite';
import { Tree, Loading } from '@alifd/next';
import styles from './index.module.scss';
import { useTreeAction } from '../hooks';
import { useStore } from '@/hooks';

const ROOT = '_root';
const ROOT_POS = '0-0';

let selectedPos = '';
const DataTree = observer(({ dict }) => {
  const { dictTreeStore: store } = useStore();
  const { dictId } = dict;
  const [treeAction] = useTreeAction();
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState([]);
  const selectedId = store.treeSelectedId;
  const { selectedItem } = store;
  const [treeState, setTreeState] = useState({ expandedKeys: [], selectedKeys: [], authExpandParent: false });
  const mapper = (item) => ({ label: item.name, key: item.itemId }); // 将dictItem转化为tree需要的数据
  useEffect(() => {
    // 初始化tree
    store.top(dict.dictId).then((topItems) => {
      const children = topItems.map(mapper) || [];
      setData([{ label: dict.name, key: ROOT, children }]);
      const defalutSelectedId = topItems.length > 0 ? topItems[0]?.itemId : '';
      setTreeState({ ...treeState, expandedKeys: [ROOT], selectedKeys: [defalutSelectedId || ROOT] });
      // 设置selectedKeys不触发onSelect，直接设置selectedPos
      selectedPos = defalutSelectedId ? '0-0-0' : ROOT_POS;
      defalutSelectedId && store.setSelectedId(defalutSelectedId);
      // console.log('DataTree effect on dict: ', data, treeState);
    }).finally(() => setLoading(false));
  }, [dict]);
  useEffect(() => {
    // 用于修改name时，同步修改树节点显示
    // console.log('effect on item 88888888 selectedPos: %s, selectedItem: ', selectedPos, toJS(selectedItem));
    if (!data || !selectedPos) return;
    const nodeData = nodeDataByPos(selectedPos);
    if (nodeData?.key !== selectedId || !selectedItem || nodeData.label === selectedItem.name) return;
    nodeData.label = selectedItem.name;
    setData([...data]);
  }, [selectedId]);
  useEffect(() => {
    // 树节点的添加，删除操作
    if (treeAction?.action === 'adding') {
      const added = treeAction.data;
      reloadChildren(added.parentId, selectedPos).then(() => {
        setTreeState({
          ...treeState,
          expandedKeys: [...treeState.expandedKeys, added.parentId],
          // selectedKeys: [added.itemId],
        });
      });
    }
    if (treeAction?.action === 'deleting') {
      const deleted = treeAction.data;
      const parentPos = deleted.parentId ? selectedPos.split('-').slice(0, -1).join('-') : ROOT_POS;
      const parentNodeData = nodeDataByPos(parentPos);
      const deletedIndex = selectedPos.slice(-1);
      parentNodeData.children = parentNodeData.children.filter((d) => d.key !== deleted.itemId);
      const newSelKey = deletedIndex === '0' ? deleted.parentId : parentNodeData.children[deletedIndex - 1].key;
      selectedPos = `${parentPos}-${deletedIndex - 1}`;
      setTreeState({ ...treeState, selectedKeys: [newSelKey] });
      store.setSelectedId(newSelKey);
    }
  }, [treeAction]);
  // console.log('tree render 9999999 selectedItem: ', toJS(store.selectedItem));

  function reloadChildren(parentId, pos) {
    const nodeData = nodeDataByPos(pos);
    if (!nodeData) {
      console.error('No nodeData: ', nodeData);
      return;
    }
    return store.children(dictId, parentId).then((children) => {
      nodeData.children = children.map(mapper);
      // setData(...data);
      if (!children || children.length === 0) {
        nodeData.isLeaf = true;
      }
      return Promise.resolve();
    });
  }

  const onLoadData = (node) => {
    // 点击和回车的回调数据不一致？
    if (node?.props?.children || node?.node?.props?.children) {
      return Promise.resolve();
    }
    const { eventKey: parentId, pos } = node.props || node?.node?.props;
    return reloadChildren(parentId, pos);
  };

  function nodeDataByPos(pos) {
    return pos.split("-").slice(1).reduce((ret, num) => ret?.children?.[num], { children: data });
  }

  return (
    <div className={styles.treePanel}>
      <Loading visible={loading} shape="fusion-reactor" className={styles.loading}>
        {/* <Search shape="simple" size="medium" onChange={handleSearch} /> */}
        {treeState.expandedKeys.length > 0 && <Tree
          dataSource={data}
          onSelect={(keys, extra) => {
            if (!keys?.length) return;
            setTreeState({ ...treeState, selectedKeys: keys });
            // 点击和回车的回调数据不一致？
            selectedPos = extra?.node?.props?.pos || extra?.node.pos;
            store.setSelectedId(keys?.[0]);
            // console.log('-----onSelect pos: %s, treeState: %o', selectedPos, treeState, data, extra);
          }}
          onExpand={(keys) => {
            setTreeState({ ...treeState, expandedKeys: keys });
          }}
          loadData={onLoadData}
          autoExpandParent={treeState.authExpandParent}
          expandedKeys={treeState.expandedKeys}
          selectedKeys={treeState.selectedKeys}
          // filterTreeNode={filterTreeNode}
          isNodeBlock={{ defaultPaddingLeft: 20, indent: 10 }}
        />}
      </Loading>
    </div>
  );
});

export default DataTree;
